const constants  = require("../../data/constants");
const adminModel = require('../../model/admin');
var UUID         = require('uuid');

let admin ={};
let tokens={};
/**
  登陆
 * @param {*} req 
 * @param {*} res 
 */
admin.checklogin=async(req,res)=>{
    
    let username = req.body.username;
    let password = req.body.password;
    if(!username || !password){
        res.send(constants.httpCode.ILLEGAL_PARAM);
    }else{
        await adminModel.checklogin(username,password).then((data)=>{
            console.log('then then',username,password, data);
            if(data && data.length>0){
                let token = UUID.v1().replace(/-/g,'');
                tokens[token] = {
                    token:data,
                    name:username
                };
                res.send( Object.assign(constants.httpCode.OK , {data:{token:token,
                    avatar: 'assets/images/user.png',
                    name:username
                }}));
            }else{
                res.send(Object.assign(constants.httpCode.PASS_ERROR, {data:{}}));
            }
            
        }).catch((err)=>{
            console.error(err)
            res.send(constants.httpCode.ILLEGAL_PARAM);
        });
    }
}

// 注销
admin.logout=function(req,res){
    let token = req.header('X-Token');
    if(tokens[token]){
        res.send(Object.assign(constants.httpCode.OK,{data:{}}));
    }
    else{
        res.send(Object.assign(constants.httpCode.ILLEGAL_TOKEN, {data:{}}));
    }
    
}

// 用户信息
admin.info=function(req,res){
    let token = req.query.token;
    if(tokens[token]){
        res.send(Object.assign(constants.httpCode.OK,{data:{
            token:token,
            avatar: 'assets/images/user.png',
            name:tokens[token].name
        }}));
    }else{
        res.send(Object.assign(constants.httpCode.ILLEGAL_TOKEN, {data:{}}));
    }
}

module.exports=admin;